package com.zlf.sb.demo.service.impl;

import com.zlf.sb.demo.dto.ProcessedUserData;
import com.zlf.sb.demo.entity.UserEntity;
import com.zlf.sb.demo.entity.UserJsonDataEntity;
import com.zlf.sb.demo.service.IUserJsonDataService;
import com.zlf.sb.demo.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

@Slf4j
@Service
public class UserDataProcessor {
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserJsonDataService userJsonDataService;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;


    public CompletableFuture<ProcessedUserData> processUserData(
            String userId) {
        // 首先获取用户数据
        return CompletableFuture
                .supplyAsync(() ->
                                userService.getById(userId),
                        taskExecutor
                )
                .thenComposeAsync(user ->
                                // 并行获取偏好和安全检查
                                // 并行获取偏好和安全检查
                                CompletableFuture.allOf(
                                        userService
                                                .fetchPreferencesAsync(userId),
                                        userService
                                                .performSecurityCheckAsync(user)
                                )
                                        .thenApply(ignored -> user),
                        taskExecutor
                )
                .thenApplyAsync(user -> {
                    // 使用偏好处理用户数据
                    UserEntity preferences =
                            userService.getById(userId);
                    UserJsonDataEntity securityStatus =
                            userJsonDataService.getById(user);

                    return new ProcessedUserData(
                            user,
                            securityStatus
                    );
                }, taskExecutor)
                .whenCompleteAsync((data, error) -> {
                    if (error != null) {
                        handleProcessingError(userId, error);
                    } else {
                        /*notificationService.notifyProcessingComplete(
                                userId
                        );*/
                        log.info("ok");

                    }
                }, taskExecutor);
    }

    private void handleProcessingError(String userId, Throwable error) {
        log.error(
                "处理用户数据时出错 {}: {}",
                userId,
                error.getMessage()
        );
        //notificationService.notifyProcessingFailed(userId, error);
    }
}
